import * as fs from 'fs';

/**
 * @desc 计算分页
 * @param total
 * @param pageSize
 * @param page
 * @returns
 */
export const getPagination = (
  total: number,
  pageSize: number,
  page: number,
) => {
  const pages = Math.ceil(total / pageSize);
  return {
    total,
    page,
    pageSize,
    pages,
  };
};

/**
 * @desc 将map转换为对象
 * @param {Map} map
 * @param {*} any
 * @return {*}
 */
type ObjectType = Record<string, number | string | boolean>;
export const mapToObj = (map: Map<string, any>): ObjectType => {
  const obj: ObjectType = {};
  for (const [k, v] of map) {
    obj[k] = v;
  }
  return obj;
};

// 开始递归方法
export function listToTree(params) {
  const result = [];
  for (const param of params) {
    if (!param.parent_id) {
      // 判断是否为顶层节点
      const parent = {
        // id: param.id,
        // label: param.name,
        ...param,
        children: [],
      };
      parent.children = getchilds(param.id, params); // 获取子节点
      result.push(parent);
    }
  }
  return result;
}

function getchilds(id, array) {
  const childs = [];
  for (const arr_item of array) {
    // 循环获取子节点
    if (arr_item.parent_id === id) {
      childs.push({
        ...arr_item,
        // id: arr_item.id,
        // label: arr_item.name,
      });
    }
  }
  for (const child of childs) {
    // 获取子节点的子节点
    const childscopy = getchilds(child.id, array); // 递归获取子节点
    if (childscopy.length > 0) {
      child.children = childscopy;
    }
  }
  return childs;
}

export const checkDirAndCreate = (filePath) => {
  const pathArr = filePath.split('/');
  let checkPath = '.';
  let item: string;
  for (item of pathArr) {
    checkPath += `/${item}`;
    if (!fs.existsSync(checkPath)) {
      fs.mkdirSync(checkPath);
    }
  }
};
